package org.gas

/*
* 获取Docker官方仓库crt证书
* Jdk17
* Kotlin 1.8.20
* Scala 3.2.2
* By gas
* */

import java.net.URL
import java.util.Base64
import javax.net.ssl.HttpsURLConnection
import java.io.{BufferedWriter, File, FileWriter}
import java.security.cert.{Certificate, X509Certificate}


object Applic {
    private val host: String = "index.docker.io"
    private val crtPath: String = s"/etc/ssl/certs/$host.crt"
    private val crtFile: BufferedWriter = new BufferedWriter(new FileWriter(crtPath, true))

    def main(args: Array[String]): Unit = {
        // 连接网站
        val url: URL = new URL(s"https://$host:443")
        val conn: HttpsURLConnection = url.openConnection.asInstanceOf[HttpsURLConnection]
        conn.connect()
        // 获取证书
        val crt: Array[Certificate] = conn.getServerCertificates
         // 保存证书
        var cPem: String = null
        for (i <- crt) {
            cPem = crtPEMFormat(i.asInstanceOf[X509Certificate])
            crtFile.write(cPem)
        }
        crtFile.close()
    }

    def crtPEMFormat(crt: X509Certificate): String =
        s"""-----BEGIN CERTIFICATE-----
           |${Base64.getEncoder.encodeToString(crt.getEncoded)}
           |-----END CERTIFICATE-----
           |""".stripMargin
}